<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="姓名" prop="username">
      <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off"/>
    </el-form-item>
    <el-form-item label="联系方式" prop="telephone">
      <el-input v-model="ruleForm.telephone" type="text" autocomplete="off"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >确认</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { userAdd } from '../../../api/user'

const ruleFormRef = ref<FormInstance>()

const validateUsername = (rule: any, value: string, callback: (data? :any) =>{}) => {
  if (value === '') {
    callback(new Error('Please input the username'))
  } else {
    if (ruleForm.password !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('username', () => null)
    }
    callback()
  }
}
const validatePassword = (rule: any, value: string, callback: (data? :any) =>{}) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else if (value !== '' && value.length <= 5) {
    callback(new Error('Password must be greater than 6 digits'))
  } else {
    callback()
  }
}
const validateTelephone = (rule:any, value: string, callback: (data? :any) =>{}) => {
  const reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/
  if (value === '') {
    callback(new Error('Please input the telephone'))
  } else if (!reg.test(value)) {
    callback(new Error('Password input surefire telephone'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  password: '',
  telephone: ''
})
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  telephone: [{ validator: validateTelephone, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await userAdd({
        username: ruleForm.username,
        password: ruleForm.password,
        telephone: ruleForm.telephone
      })
      if (!formEl) return
      formEl.resetFields()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
